<?php

/**
 * 应用程序的公共控制器基础类
 *
 * 可以在这个类中添加方法来完成应用程序控制器共享的功能。
 */
abstract class Controller_Abstract extends QController_Abstract
{
	/**
	 * 2011-9-18
	 */
	protected $curr_page=1;	
	protected $page_size=10; 
	//排序列
	protected $orderkey='ids';
	//排序方式
	protected $ordertype='asc';
	
	//分页参数
	protected $pagination = null;
	
	//搜索参数
	protected $param=null;
	
	/**
	 * 
	 *2011-12-23-下午11:58:03 by 460932465
	 * @access 通用删除...
	 * @param 条件数组 $array
	 * @param 删除模式
	 */
	function delete($array,$mode = NULL)
	{
		QDB::getConn()->startTrans();
		try {
		$this->union_table->deleteWhere($array);
		QDB::getConn()->completeTrans(true);	
		} catch (Exception $e) {
		QDB::getConn()->completeTrans(FALSE);
		return $this->error($e->getmessage());	
		}
		return $this->success('删除成功');
	}
	/**
	 * 
	 *2011-12-22-下午05:16:37 by 460932465
	 * @access 通用搜索...
	 */
 	function lists($append_data = NULL)
	{
		//获取搜索参数
		$this->get_param();
		//初始化分页信息
		$this->_format_page_info();
		//关联表
		//$this->union_table = $union_table;
		if (!is_null($append_data))$this->param = array_merge($this->param,$append_data);
		$dis_param = new helper_disposeparam($this->param);
		$obj = call_user_func_array(array($this->union_table,'find'), $dis_param->getsql());
		$item = $obj->limitPage($this->curr_page,$this->page_size)
					->order(' '.$this->orderkey.' '.$this->ordertype)
					->fetchPagination($this->pagination)
					->getall();
		$this->_view['item'] = $item;
		$this->_view['pagination'] = $this->pagination;	
	}
	
	
	
	//通用修改
	//protected $union_table = NULL; //关联数据表 exp Orders::meta()
	/**
	 * 
	 *2011-12-20-下午12:45:32 by 460932465
	 * @return 成功返回true 失败返回错误字符串
	 * 
	 * @param FORM对象 $form
	 * @param 主键列名 $pkname
	 * @param 附加数据 $appendData
	 */
	/*
	 *  function add($form,$pkname,$appendData = NULL)
	{
		if (is_null($this->union_table))
		{			
			return '对不起,关联数据表未设置';
		}
		//$url = url($this->_context->controller_name.'/'.$this->_context->action_name);
		//$TempForm = 'Form_'.$this->_context->controller_name.$this->_context->action_name;
		//获取主键
		//$idkey = $this->union_table->table->getPK();
		//如果是数组 取第1个键
		//if (is_array($idkey))
		//{
		//	$idkey = array_shift($idkey);
		//}
		$id = intval($this->_context->$pkname);
		$form_data = null;
		//如果是修改操作
		if($id)
		{
			$form_data = $this->union_table->find($id)->getone();
			if (!$form_data->id())
			{
				return '不存在数据';
			}
		}
		
		//创建表单对象
			//$form = new $TempForm($url);
			
		//如果是GET 数据 存在 新加 || 编辑
		if ($this->_context->isGET())
		{
			if (!is_null($form_data) && !is_null($appendData))
			{
				$form_data = array_merge($form_data->toArray(),$appendData);
			}else if (!is_null($form_data))
			{
				$form_data = $form_data->toArray();
			}else if(!is_null($appendData))
			{
				$form_data = $appendData;
			}
				//存在数据
			if (!is_null($form_data))
			{
			$form->import($form_data);
			}
		$this->_view['form'] = $form;	
		}else if ($this->_context->isPOST())
		{
			if ($form->validate($_POST))
			{
				//获取内容
				$form_values = $form->values();
				//如果是新加入
				if (is_null($form_data))
				{
					$form_database_obj = $this->union_table->newObject($form_values);
				}else
				{
					$form_database_obj = $form_data->changeProps($form_values);
				}
				//开始更新 开启事务
				QDB::getConn()->startTrans();
				try {
					$form_database_obj->save(); //默认99级
					QDB::getConn()->completeTrans(true);
				} catch (Exception $e) {
					//失败回滚
					QDB::getConn()->completeTrans(false);
					//返回错误
					return $this->error($e->getMessage());
				}
				//成功修改
				return $this->success('数据编辑成功');
				
			}else 
			{//验证失败返回错误信息
				return $this->error($form->errorMsg());
			}
		}
		
	}
	 */
	//------------
	/**
	 * 
	 *2011-12-20-下午02:13:02 by 460932465
	 * @access 初始化分页信息...
	 */
	protected function _format_page_info()
	{
		//当前页码
		$this->curr_page= isset($this->_context->pageNum)?intval($this->_context->pageNum):1;
		$this->orderkey=isset($this->_context->orderkey)?trim($this->_context->orderkey):'id';
		$this->ordertype=isset($this->_context->ordertype)?$this->_context->ordertype:'desc';
		$this->page_size=isset($this->_context->numPerPage)?intval($this->_context->numPerPage):$this->page_size;
		
		
		//dump($this->param);
	}
	/**
	 * 
	 * 成功返回DWZ 格式...
	 * @param 提示信息 $message
	 */
	protected function success($message)
	{
		$this->_dwzjson(200, $message);
	}
	/**
	 * 
	 * 失败返回DWZ 格式...
	 * @param 提示信息 $message
	 */
	protected function error($message)
	{
		$this->_dwzjson(300, $message);
	}
	/**
	 * 
	 *2011-12-17-下午08:26:40 by 460932465
	 * @return 登陆超时
	 * @param unknown_type $message
	 */
	protected function nologin($message)
	{
		$this->_dwzjson(301, $message);
	}
	/**
	 * 
	 *2011-2011-12-17-下午08:16:46 by 460932465
	 * @return JSon to dwz
	 * @param int $state
	 * @param string $message
	 */
	protected function _dwzjson($state,$message)
	{
		$navTabId=isset($this->_context->navTabId)?$this->_context->navTabId:null;
		$callbackType=isset($this->_context->callbackType)?$this->_context->callbackType:null;
		$forwardUrl=isset($this->_context->forwardUrl)?$this->_context->forwardUrl:NULL;
		$result=array(
			'statusCode'=>$state,
			'message'=>$message,
			'navTabId'=>$navTabId,
			'callbackType'=>$callbackType,
			'forwardUrl'=>$forwardUrl
		);
			exit(json_encode($result));
	}	
	//-------------------------------------------------------end by
    /**
     * 控制器动作要渲染的数据
     *
     * @var array
     */
    protected $_view = array();

    /**
     * 控制器要使用的视图类
     *
     * @var string
     */
    protected $_view_class = 'QView_Render_PHP';

    /**
     * 控制器要使用的视图
     *
     * @var string
     */
    protected $_viewname = null;

    /**
     * 控制器所属的应用程序
     *
     * @var CommunityApp
     */
    protected $_app;

    /**
     * 构造函数
     */
    function __construct($app)
    {
        parent::__construct();
        $this->_app = $app;
    }

    /**
     * 执行指定的动作
     *
     * @return mixed
     */
    function execute($action_name, array $args = array())
    {
        $action_method = "action{$action_name}";

        // 执行指定的动作方法
        $this->_before_execute();

        #IFDEF DBEUG
        QLog::log('EXECUTE ACTION: '. get_class($this) . '::' . $action_method . '()', QLog::DEBUG);
        #ENDIF
        $response = call_user_func_array(array($this, $action_method), $args);
        $this->_after_execute($response);
        if (is_null($response) && is_array($this->_view))
        {
            // 如果动作没有返回值，并且 $this->view 不为 null，
            // 则假定动作要通过 $this->view 输出数据
            $config = array('view_dir' => $this->_getViewDir());
            $response = new $this->_view_class($config);
            $response->setViewname($this->_getViewName())->assign($this->_view);
            $this->_before_render($response);
        }
        elseif ($response instanceof $this->_view_class)
        {
            $response->assign($this->_view);
            $this->_before_render($response);
        }

        return $response;
    }

    /**
     * 指定的控制器动作未定义时调用
     *
     * @param string $action_name
     */
    function _on_action_not_defined($action_name)
    {
    }

    /**
     * 执行控制器动作之前调用
     */
    protected function _before_execute()
    {
    	// 先放一个假的 哟西
    	//$_SESSION[Helper_Users_Login::$_Login_SessionKey] = array(
    	//	'userid'=>5,
    	//	'email'=>'itengine@qq.com'
    	//);
    	// 配置加载
    	$this->_view['_UDI'] = $this->_context->requestUDI();
    	$config = Configs::find()->order('id desc')->asArray()->getOne();
		if ($config && $config['isopen'] && $this->_context->ns != 'admin'){
			echo $config['closewhy'];exit;
		}
		$this->_view['config'] = $config;
    	// 验证用户登陆状态
    	if ($this->_context->ns == 'admin' 
    			&& $this->_context->controller_name != 'login' 
    			&& $this->_context->controller_name != 'main') {
    		if (!$this->_check_admin())
    		{
    			// 没有登录
    			echo json_encode(array(
					'statusCode'=>Helper_Dwz::DWZ_STATUS_TIME_OUT,
					'message'=>'对不起,您还没有登陆不能操作后台功能!',
					'navTabId'=>'',
					'callbackType'=>'closeCurrent',
					'forwardUrl'=>''));exit;
    		}else{
    			// 登录了 , 验证权限
    			$namespace = $this->_context->ns;
    			$module = $this->_context->module_name?$this->_context->module_name:'default';
    			$controller_name = $this->_context->controller_name;
    			$action_name = $this->_context->action_name;
    			$power = unserialize($_SESSION['ADMIN_USER']['power']);
    			if (!isset($power[$module][$namespace][$controller_name][$action_name]))
    			{
    				$menus_obj = Functions::find('module = ? and namespace = ? and controller =? and action = ?',$module,$namespace,$controller_name,$action_name)->getOne();
    				if ($menus_obj->ispower){
	    				echo json_encode(array(
						'statusCode'=>Helper_Dwz::DWZ_STATUS_ERROR,
						'message'=>'对不起,您没有权限操作此功能!',
						'navTabId'=>'',
						'callbackType'=>'closeCurrent',
						'forwardUrl'=>''));exit;
    				}
    			}
    		}
    	}
    }

    /**
     * 执行控制器动作之后调用
     *
     * @param mixed $response
     */
    protected function _after_execute(& $response)
    {
    }

    /**
     * 渲染之前调用
     *
     * @param QView_Render_PHP
     */
    protected function _before_render($response)
    {
    }

    /**
     * 准备视图目录
     *
     * @return array
     */
    protected function _getViewDir()
    {
        if ($this->_context->module_name)
        {
            $dir = Q::ini('app_config/MODULE_DIR') . "/{$this->_context->module_name}/view";
        }
        else
        {
            $dir = Q::ini('app_config/APP_DIR') . '/view';
        }

        if ($this->_context->ns)
        {
            $dir .= "/{$this->_context->ns}";
        }
        return $dir;
    }

    /**
     * 确定要使用的视图
     *
     * @return string
     */
    protected function _getViewName()
    {
        if ($this->_viewname === false)
        {
            return false;
        }
        $viewname = empty($this->_viewname) ? $this->_context->action_name : $this->_viewname;
        return strtolower("{$this->_context->controller_name}/{$viewname}");
    }

    /**
     * 显示一个提示页面，然后重定向浏览器到新地址
     *
     * @param string $caption
     * @param string $message
     * @param string $url
     * @param int $delay
     * @param string $script
     *
     * @return QView_Render_PHP
     */
    protected function _redirectMessage($caption, $message, $url, $delay = 3, $script = '')
    {
        $config = array('view_dir' => $this->_getViewDir());
        $response = new $this->_view_class($config);
        $response->setViewname('redirect_message');
        $response->assign(array(
            'message_caption'   => $caption,
            'message_body'      => $message,
            'redirect_url'      => $url,
            'redirect_delay'    => $delay,
            'hidden_script'     => $script,
        ));
        return $response;
    }
    /**
     * 
     *2011-12-20-下午04:25:56 by 460932465
     * @access 获取查询参数数组 ...
     */
	protected function get_param()
	{
		$this->param=$this->_context->get();
		unset($this->param['ns']);
		unset($this->param['controller']);
		unset($this->param['action']);
		unset($this->param['module']);
		
		if(isset($this->param['numPerPage']))
		{
			unset($this->param['numPerPage']);
		}
		if(isset($this->param['pageNum']))
		{
			unset($this->param['pageNum']);
		}
		if(isset($this->param['numPerPage']))
		{
			unset($this->param['numPerPage']);
		}
		if(isset($this->param['undefined']))
		{
			unset($this->param['undefined']);
		}
		
		if (isset($this->param['_']))unset($this->param['_']);
		
		//设置搜索POST的地址
		$this->_view['param']=$this->param;
	}
	protected function pase_param($array)
	{
		$result = null;
		$Qdb = QDB_Cond::create();
		foreach ($array as $k=>$v)
		{
			if(strpos('_option', $k))continue;
			if (isset($array[$k.'_option']))
			{
				$option = $array[$k.'_option'];
				if (is_array($option))
				{
					if (isset($option['link']) && $option['link'] == 'or')
					{
						$Qdb->orCond(array($k=>$v));
					}else
					{
						$Qdb->andCond(array($k=>$v));
					}
				}else 
				{
					if ($option == 'or')
					{
						$Qdb->orCond(array($k=>$v));
					}else
					{
						$Qdb->andCond(array($k=>$v));
					}
				}
			}else
			{
						$Qdb->andCond(array($k=>$v));
			}
			
		}
		
		return $Qdb;
	}
	
	function _check_admin()
	{
		return isset($_SESSION['ADMIN_USER']) && $_SESSION['ADMIN_USER'];
	}
}

